package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"live-broadcast/dao"
	"live-broadcast/dao/queue"
	"live-broadcast/model"
	"live-broadcast/request"
	"live-broadcast/response"
	"log"
	"net/http"
	"path/filepath"
)

func Add(c *gin.Context) {
	var req request.Live_RoomAdd
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	user_id := c.GetUint("userId")
	room := model.LiveRoom{
		UserId: user_id,
		Type:   1,
	}
	dao.Create(&room)
	if room.Id == 0 {
		response.ResponseError(c, "直播间创建失败", nil)
		return
	}
	liveBroadcast := model.LiveBroadcastUser{

		LiveRoom: int64(room.Id),
		UserId:   user_id,
		Name:     req.Name,
		Gender:   req.Gender,
		UserType: 2,
	}
	dao.Create(&liveBroadcast)
	if liveBroadcast.Id == 0 {
		response.ResponseError(c, "直播间人员添加失败", nil)
		return
	}
	queue.PublishPub("LiveBroadcast", room.Id)
	response.ResponseSuccess(c, "直播间创建成功", room)
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	name := filepath.Ext(file.Filename)
	if name != ".png" && name != ".jpg" {
		response.ResponseError(c, "图片格式不正确", nil)
		return
	}
	dst := "D:\\gocode\\src\\gao3\\2\\rk\\3\\12\\zhoukao3\\live-broadcast\\sotrc\\upload\\" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)

	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))

}

func List(c *gin.Context) {
	user_id := c.GetUint("userId")
	Room := []model.LiveRoom{}
	err := dao.Wheres(&model.LiveRoom{UserId: user_id}, &Room)
	if err == false {
		response.ResponseError(c, "失败", err)
	}
	response.ResponseSuccess(c, "查询成功", Room)
}

func AddUser(c *gin.Context) {
	var req request.Live_RoomAdd
	user_id := c.GetUint("userId")
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	data := model.LiveBroadcastUser{

		LiveRoom: 3,
		UserId:   user_id,
		Name:     req.Name,
		Gender:   req.Gender,
		UserType: 1,
	}
	queue.PublishPub("AddUser", data)
	response.ResponseSuccess(c, "进入直播间", data)
}

func Updated(c *gin.Context) {
	var req request.UpdatedRoom
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	data := model.LiveRoom{
		Type: 2,
	}
	dao.Updated(&model.LiveRoom{Id: req.Id}, &data)
	response.ResponseSuccess(c, "修改成功", data)
}

func ListRoom(c *gin.Context) {
	var req request.ListRoom
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	Room := []model.LiveRoom{}
	if dao.Wheres(&model.LiveRoom{UserId: req.RoomId}, &Room) == false {
		response.ResponseError(c, "失败", err)
	}
	a1 := len(Room)
	var fensi = 0.1 - float32(10000.0-a1)*10000.0
	response.ResponseSuccess(c, "ok", fensi)
}
